//
//  ScanQRcode.m
//  QRcode_GHdemo
//
//  Created by xiangwang on 16/6/28.
//  Copyright © 2016年 Hope. All rights reserved.
//

#import "ScanQRcode.h"
#import <Masonry/Masonry.h>
#define GH_WIDTH    [[UIScreen mainScreen] bounds].size.width
#define GH_HEIGHT   [[UIScreen mainScreen] bounds].size.height
@interface ScanQRcode ()<UIActionSheetDelegate>

@end

@implementation ScanQRcode

- (void)initNavigation{
    UIView *viewBg = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 64)];
    viewBg.backgroundColor = [UIColor clearColor];
    [self.view addSubview:viewBg];
    
    UILabel *labTitle = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, WIDTH, 44)];
    labTitle.text = @"二维码";
    labTitle.textColor = [UIColor whiteColor];
    labTitle.textAlignment = NSTextAlignmentCenter;
    labTitle.font = [UIFont systemFontOfSize:18];
    [viewBg addSubview:labTitle];
    
    UIButton *btnBack = [[UIButton alloc] initWithFrame:CGRectMake(0, 20, 44, 44)];
    [btnBack setImage:[UIImage imageNamed:@"btnBackNormal"] forState:UIControlStateNormal];
    [btnBack setImage:[UIImage imageNamed:@"btnBackSelect"] forState:UIControlStateHighlighted];
    [btnBack addTarget:self action:@selector(btnBackClicked) forControlEvents:UIControlEventTouchUpInside];
    [viewBg addSubview:btnBack];
    
    UIButton *btnDetail = [[UIButton alloc] initWithFrame:CGRectMake(WIDTH-44, 20, 44, 44)];
    [btnDetail setImage:[UIImage imageNamed:@"detail"] forState:UIControlStateNormal];
    [btnDetail addTarget:self action:@selector(btnDetailClicked) forControlEvents:UIControlEventTouchUpInside];
    [viewBg addSubview:btnDetail];
}

- (void)btnBackClicked{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)btnDetailClicked{
    UIActionSheet *actionSheet = [[UIActionSheet alloc]
                                  initWithTitle:nil
                                  delegate:self
                                  cancelButtonTitle:@"取消"
                                  destructiveButtonTitle:nil
                                  otherButtonTitles:@"从相册中选择图片", nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
    [actionSheet showInView:self.view];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor grayColor];
    [self initNavigation];
    
//    UIButton * scanButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
//    [scanButton setTitle:@"取消" forState:UIControlStateNormal];
//    [scanButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
//    scanButton.frame = CGRectMake(100, 430, GH_WIDTH-200, 50);
//    [scanButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:scanButton];
    
    UILabel * labIntroudction= [[UILabel alloc] initWithFrame:CGRectMake(20, 430, GH_WIDTH-40, 50)];
    labIntroudction.backgroundColor = [UIColor clearColor];
    labIntroudction.textAlignment = NSTextAlignmentCenter;
    labIntroudction.textColor=[UIColor whiteColor];
    labIntroudction.text=@"将二维码放入框内,即可自动扫描";
    [self.view addSubview:labIntroudction];
    
    _device = [ AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    _input = [ AVCaptureDeviceInput deviceInputWithDevice:self.device error:nil];
    
    _output = [[ AVCaptureMetadataOutput alloc]init];
    [ _output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    _session = [[ AVCaptureSession alloc]init];
    [ _session setSessionPreset:AVCaptureSessionPresetHigh];
    if ([ _session canAddInput:self.input])
    {
        [ _session addInput:self.input];
    }
    if ([ _session canAddOutput:self.output])
    {
        [ _session addOutput:self.output];
    }
    
    _output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode];
    [ _output setRectOfInterest : CGRectMake (( 124 )/ GH_HEIGHT ,(( GH_WIDTH - 220 )/ 2 )/ GH_WIDTH , 220 / GH_HEIGHT , 220 / GH_WIDTH )];
    
    _preview =[AVCaptureVideoPreviewLayer layerWithSession:_session];
    _preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
    _preview.frame = self.view.layer.bounds;
    //    _preview.tor
    [self.view.layer insertSublayer:_preview atIndex:0];
    
    
    //扫描框
    imageView = [[UIImageView alloc]initWithFrame:CGRectMake((GH_WIDTH-(GH_WIDTH-GH_WIDTH*0.5f))/2,GH_HEIGHT*0.2f,GH_WIDTH- GH_WIDTH*0.5f,GH_WIDTH-GH_WIDTH*0.5f)];
//    imageView.image = [UIImage imageNamed:@"pick_bg"];
    imageView.layer.borderColor = [UIColor whiteColor].CGColor;
    imageView.layer.borderWidth = 2.0;
    [self.view addSubview:imageView];
    upOrdown = NO;
    num =0;
    
    _line = [[UIImageView alloc] initWithFrame:CGRectMake((GH_WIDTH-(GH_WIDTH-GH_WIDTH*0.5f))/2,GH_HEIGHT*0.2f,GH_WIDTH- GH_WIDTH*0.5f,1)];
    
    _line.image = [UIImage imageNamed:@"line.png"];
    [self.view addSubview:_line];
    timer = [NSTimer scheduledTimerWithTimeInterval:.02 target:self selector:@selector(animation1) userInfo:nil repeats:YES];
    
    [ _session startRunning ];
    
    
}
#pragma mark -
#pragma mark - 上下动画
-(void)animation1
{
    if (upOrdown == NO) {
        num ++;
        _line.frame = CGRectMake((GH_WIDTH-(GH_WIDTH-GH_WIDTH*0.5f))/2, GH_HEIGHT*0.2f+2*num, imageView.frame.size.width, 2);
        if (2*num > GH_WIDTH-GH_WIDTH*0.5f-5) {
            upOrdown = YES;
        }
    }
    else {
        num --;
        _line.frame = CGRectMake((GH_WIDTH-(GH_WIDTH-GH_WIDTH*0.5f))/2, GH_HEIGHT*0.2f+2*num, imageView.frame.size.width, 2);
        if (num == 2) {
            upOrdown = NO;
        }
    }
    
}
#pragma mark -
#pragma mark - 取消按钮
-(void)backAction
{
    _line.hidden = NO;
    [ _session startRunning ];
    
}
#pragma mark -
#pragma mark - AVCaptureMetadataOutputObjectsDelegate

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:( AVCaptureConnection *)connection
{
    NSString *stringValue;
    if ([metadataObjects count] > 0 )
    {
        // 停止扫描
        [ _session stopRunning ];
        AVMetadataMachineReadableCodeObject * metadataObject = [metadataObjects objectAtIndex:0];
        stringValue = metadataObject.stringValue;
        _line.hidden = YES;//隐藏动画效果
        NSLog(@"扫描结果=%@",stringValue);
        
        [[NSNotificationCenter defaultCenter]postNotificationName:@"QRCode" object:stringValue];
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self myPhoto];
    }
}

#pragma mark - 我的相册
- (void)myPhoto{
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]){
        //1.初始化相册拾取器
        UIImagePickerController *controller = [[UIImagePickerController alloc] init];
        //2.设置代理
        controller.delegate = self;
        //3.设置资源：
        /**
         UIImagePickerControllerSourceTypePhotoLibrary,相册
         UIImagePickerControllerSourceTypeCamera,相机
         UIImagePickerControllerSourceTypeSavedPhotosAlbum,照片库
         */
        controller.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        //4.随便给他一个转场动画
        controller.modalTransitionStyle=UIModalTransitionStyleCrossDissolve;
        [self presentViewController:controller animated:YES completion:NULL];
        
    }else{
        NSLog(@"设备不支持访问相册，请在设置->隐私->照片中进行设置！");
    }
}

#pragma mark- ImagePickerController delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    //1.获取选择的图片
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    //2.初始化一个监测器
    CIDetector*detector = [CIDetector detectorOfType:CIDetectorTypeQRCode context:nil options:@{ CIDetectorAccuracy : CIDetectorAccuracyHigh }];
    [picker dismissViewControllerAnimated:YES completion:^{
        //监测到的结果数组
        NSArray *features = [detector featuresInImage:[CIImage imageWithCGImage:image.CGImage]];
        if (features.count >=1) {
            /**结果对象 */
            CIQRCodeFeature *feature = [features objectAtIndex:0];
            NSString *scannedResult = feature.messageString;
            if (scannedResult) {
                NSString *contents = scannedResult;
                if ([contents containsString:@"http://"]) {
//                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:contents]];
                    NSLog(@"扫描结果：%@",contents);
                    [[NSNotificationCenter defaultCenter]postNotificationName:@"QRCode" object:contents];
                    [self dismissViewControllerAnimated:YES completion:nil];
                }else{
                    NSLog(@"扫描结果：%@",contents);
                }
            }
        }
        else{
            NSLog(@"该图片没有包含一个二维码！");
        }
    }];
}



@end
